<?php

namespace App\Traits;


use Illuminate\Database\Eloquent\Builder;

/**
 * 使用联合主键
 */
trait HasCompositePrimaryKey
{
    /**
     * Get the value indicating whether the IDs are incrementing.
     *
     * @return bool
     */
    public function getIncrementing(): bool
    {
        return false;
    }

    /**
     * Set the keys for a save update query.
     * @param Builder $query
     * @return Builder
     * @throws \Exception
     */
    protected function setKeysForSaveQuery(Builder $query): Builder
    {
        foreach ($this->getKeyName() as $key) {
            if ($this->$key)
                $query->where($key, '=', $this->$key);
            else
                throw new \Exception(__METHOD__ . 'Missing part of the primary key: ' . $key);
        }

        return $query;
    }
    /**
     *
     * 按标识对单个记录执行查询.
     *
     * @param array  $ids 复合主键数组 例如 [column1 => value1,column1 => value1].
     * @param array $columns
     * @return Builder|Model|object|null
     */
    public static function find(array $ids, array $columns = ['*'])
    {
        $model = new self;
        $query = $model->newQuery();
        foreach ($model->getKeyName() as $key) {
            $query->where($key, '=', $ids[$key]);
        }
        return $query->first($columns);
    }
}